const { Controller, } = require('egg')
const { getResult } = require('../assets/utils')

class TopicController extends Controller {
  // POST
  async create() {
    const { ctx, } = this
    const result = await ctx.service.topic.create(ctx.request.body)
    let data = {}
    if (result.affectedRows === 1) {
      data = {
        msg: '新增成功',
      }
    } else {
      data = {
        code: 504,
        msg: '新增文章失败',
      }
    }
    ctx.body = getResult(data)
  }

  // GET list
  async index() {
    const { ctx, } = this
    const topics = await ctx.service.topic.getTopics()
    const topicTypes = await ctx.service.topicType.fetch()
    topics.map(topic => {
      topic.type = topicTypes.find(topicType => topicType.typeId === topic.typeId)
      delete topic.typeId
    })
    ctx.body = getResult({
      data: topics
    })
  }

  // GET item
  async show() {
    const { ctx } = this
    const { id } = ctx.params
    const topic = await ctx.service.topic.getTopic(id)
    const topicTypes = await ctx.service.topicType.fetch()
    topic.type = topicTypes.find(topicType => topicType.typeId === topic.typeId)
    topic.type && delete topic.typeId
    ctx.body = getResult({
      data: topic
    })
  }
}

module.exports = TopicController
